package response

import (
	file2 "client/file"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
)

type statusType string

var (
	StatusErr statusType = "error"
	StatusOk  statusType = "ok"
)

type Response struct {
	Status  statusType `json:"status"`
	Data    any        `json:"data,omitempty"`
	Message string     `json:"message,omitempty"`
}

func (r *Response) GetRespFileMeta() (*file2.FileMeta, error) {
	obj, ok := r.Data.(map[string]interface{})
	if !ok {
		return nil, errors.New("data is not map")
	}
	bs, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}
	fileMeta := &file2.FileMeta{}
	err = json.Unmarshal(bs, fileMeta)
	if err != nil {
		return nil, err
	}
	return fileMeta, nil
}

func (r *Response) GetRespSliceInt() ([]int, error) {
	slice, ok := r.Data.([]interface{})
	if !ok {
		return nil, errors.New("data is not slice")
	}
	bs, err := json.Marshal(slice)
	if err != nil {
		return nil, err
	}
	var sliceArr []int
	err = json.Unmarshal(bs, &sliceArr)
	if err != nil {
		return nil, err
	}
	return sliceArr, nil
}

func ParseResponse(res *http.Response) (*Response, error) {
	decoder := json.NewDecoder(res.Body)
	resp := &Response{}
	err := decoder.Decode(resp)
	if err != nil {
		return nil, err
	}
	switch resp.Status {
	case StatusErr:
		return nil, errors.New(resp.Message)
	case StatusOk:
		return resp, nil
	default:
		return nil, fmt.Errorf("未知响应类型： %s, code: %d\n", resp.Status, res.StatusCode)
	}
}
